package cn.xej.boot_redis02.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author <a href="mailto:enjie.xu@yunhutech.com">xiaoming</a>
 * @since 2021/6/28
 */
@RestController
public class GoodController {

    private static final String REDIS_LOCK = "lock";

    @Autowired
    private StringRedisTemplate redisTemplate;

    private Lock lock = new ReentrantLock();

    @Autowired
    private Redisson redisson;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/buy_goods")
    public String buy_goods() throws Exception {
        //当前请求的UUID + 线程名
        String value = UUID.randomUUID().toString() + Thread.currentThread().getName();

        RLock redissonLock = redisson.getLock(REDIS_LOCK);
        redissonLock.lock();

        try {
            //从redis中获取商品剩余的数量
            String o = redisTemplate.opsForValue().get("goods");
            int num = o == null ? 0 : Integer.parseInt(o);
            String str = null;

            if (num > 0) {
                int realNum = num - 1;
                redisTemplate.opsForValue().set("goods", realNum + "");
                str = "你已经成功秒杀商品，此时还剩余：" + realNum + "件" + "\t 服务器端口: " + serverPort;

            } else {
                str = "商品已经售罄/活动结束/调用超时，欢迎下次光临" + "\t 服务器端口: " + serverPort;
            }
            System.out.println(str);
            return str;
        } finally {
            // 还在持有锁的状态，并且是当前线程持有的锁再解锁
            if (redissonLock.isLocked() && redissonLock.isHeldByCurrentThread()){
                redissonLock.unlock();
            }

//            //判断是否是自己加的锁
//            if (value.equalsIgnoreCase(redisTemplate.opsForValue().get(REDIS_LOCK))){
//                redisTemplate.delete(REDIS_LOCK);
//            }
        }


        /**
        try {
            lock.lock();
            //从redis中获取商品剩余的数量
            String o = redisTemplate.opsForValue().get("goods");
            int num = o == null ? 0 : Integer.parseInt(o);
            String str = null;

            if (num>0){
                int realNum = num - 1;
                redisTemplate.opsForValue().set("goods",realNum+"");
                str = "你已经成功秒杀商品，此时还剩余：" + realNum + "件" + "\t 服务器端口: " + serverPort;
            }else {
                str = "商品已经售罄/活动结束/调用超时，欢迎下次光临" + "\t 服务器端口: " + serverPort;
            }
            System.out.println(str);
            return str;
        } finally {
            lock.unlock();
        }
         */
    }

}
